package com.example.batch.controller;

import com.example.batch.dto.ProgressInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 提供根据 batchId 查询当前批次进度的接口
 */
@RestController
@RequestMapping("/api/v1/batch")
@RequiredArgsConstructor
public class BatchStatusController {
    private final RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/status/{batchId}")
    public Object getBatchStatus(@PathVariable String batchId) {
        String key = "batch_task:" + batchId;
        Map<Object, Object> data = redisTemplate.opsForHash().entries(key);
        if (data == null || data.isEmpty()) {
            Map<String, String> errorResult = new HashMap<>();
            errorResult.put("code", "404");
            errorResult.put("message", "BatchId not found");
            return errorResult;
        }

        // 从 Redis 获取进度数据
        Integer total = (Integer) data.get("total");
        Integer success = (Integer) data.get("success");
        Integer fail = (Integer) data.get("fail");
        Integer progress = (Integer) data.get("progress");
        String status = (String) data.getOrDefault("status", "PROCESSING");

        ProgressInfo info = new ProgressInfo(total, success, fail, progress, status);
        Map<String, Object> result = new HashMap<>();
        result.put("code", "200");
        result.put("message", "SUCCESS");
        result.put("data", info);
        return result;
    }
}
